package com.sjtu.rest;

import com.sjtu.feign.UserAccountFeign;
import com.sjtu.service.LoginTokenService;
import com.sjtu.web.BaseRest;
import com.sjtu.web.Result;
import com.sjtu.web.form.LoginForm;
import com.sjtu.web.form.TokenLoginForm;
import com.sjtu.web.vo.LoginVo;
import com.sjtu.web.vo.UserAccountVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * nerine
 * 2/7/2020
 */
@RestController
public class LoginRest extends BaseRest {
    @Autowired
    private UserAccountFeign userAccountFeign;
    @Autowired
    private LoginTokenService loginTokenService;

    @PostMapping("/login")
    public Result<LoginVo> login(@Valid @RequestBody LoginForm form) {
        UserAccountVo vo = userAccountFeign.findByUserId(form.getUsername()).getData();
        if(vo == null || !checkPwdIsMatch(form.getPwd(), vo.getPassword())) {
            return success(new LoginVo(form.getUsername(), null, false, null));
        }
        String token = loginTokenService.generateToken(form.getUsername());
        return success(new LoginVo(form.getUsername(), token, true, null));
    }

    boolean checkPwdIsMatch(String input, String dbVal) {
        return input.equals(dbVal);
    }

    @PostMapping("/token-login")
    public Result<LoginVo> tokenLogin(@Valid @RequestBody TokenLoginForm form) {
        return success(new LoginVo(form.getUsername(),
                form.getToken(), loginTokenService.checkTokenIsValid(form.getUsername(), form.getToken()), null));
    }
}
